package com.ITArmy.filter;


import com.ITArmy.beans.Message;
import com.ITArmy.beans.User;
import com.ITArmy.dao.ConfigsMapper;
import com.ITArmy.dao.MessageMapper;
import com.ITArmy.dao.UserMapper;
import com.ITArmy.service.MessageService;
import com.ITArmy.service.UserService;
import com.ITArmy.util.DateChange;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//过滤器
public class LoginFilter implements Filter {

    DateChange dateChange = new DateChange();
    private static Logger logger = Logger.getLogger(LoginFilter.class);
    @Autowired
    UserMapper userMapper;
    @Autowired
    MessageService messageService;

    private FilterConfig config;

    // 销毁的方法，关闭浏览器即消失

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        System.out.println("filter被销毁了");
    }

    /**
     * 过滤的具体方法
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        boolean hasUserSession = false;
        boolean hasCookie = false;
        // 处理的是Http请求所以强转
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String url = httpServletRequest.getRequestURI();
        logger.info("请求地址为:" + url);
        // 如果用户登录过，那么session中被会加上一个特定的标识属性
        HttpSession session = httpServletRequest.getSession();
        // 看看是否能查找到这个属性
        User user = (User) session.getAttribute("user");
        if (url.contains("play")){
            chain.doFilter(request,response);
            return;
        }
        if (user != null) {
            hasUserSession = true;
            //进行进行检查一下vip
            user = dateChange.CheckVipTime(user);
            User user1 = new User();
            user1.setuId(user.getuId());
            user1.setuVip(user.getuVip());
            user1.setuExpire(user.getuExpire());
            user1.setuManage(user.getuManage());
            user1.setuHead(user.getuHead());
            System.out.println(user1.toString()+"要更新的数据");
            userMapper.updateByPrimaryKeySelective(user1);
            //进行查询是否有未读的消息，然后储存到session中
            session.setAttribute("message", messageService.getUnshowMessageNumber(httpServletRequest));
            chain.doFilter(request, response);
            return;
        } else {
            // 如果没找到说明这个访问者没有登录过这个网页。
            Cookie[] cks = httpServletRequest.getCookies();
            if (cks != null) {
                for (Cookie c : cks) {
                    if ("uId".equals(c.getName())) {// (如果)uId和cookie的名称相同
                        logger.info("输出cookie里面的值用户id为:" + c.getValue());
                        // 根据uid获取用户的信息，然后将他储存在session中
                        logger.info("uId为:" + c.getValue());
                        User user1 = userMapper.selectById(Long.parseLong(c.getValue()));
                        //进行判断一下用户的vip是否到期
                        User user2 = dateChange.CheckVipTime(user1);
                        User user3 = new User();
                        user3.setuId(user2.getuId());
                        user3.setuVip(user2.getuVip());
                        user3.setuExpire(user2.getuExpire());
                        user3.setuManage(user2.getuManage());
                        userMapper.updateByPrimaryKeySelective(user3);
                        session.setAttribute("user", user1);
                        logger.info("用户的姓名为:" + user1.getuName());
                        session.setAttribute("message", messageService.getUnshowMessageNumber(httpServletRequest));
                        hasCookie = true;
                    }
                }
            }
        }

        //放行的页面

        boolean havePoint = false;
        if (hasUserSession || url.contains("fonts") || url.contains("static") || url.contains("callback") || hasCookie || url.contains("index") || url.contains("sign") || url.contains("sendEmail")
                || url.contains("qq")   || url.contains("login") || url.contains("register") || url.contains("swagger") || url.contains("api-docs") || url.contains("checkLogin") || url.contains("findPwd")) {
            havePoint = true;
        }
        //如果想要访问后台的接口
        if (user != null) {
            if (url.contains("admin") && user.getuManage().equals("1")) {
                chain.doFilter(request, response);
                return;
            } else if (url.contains("admin") && user.getuManage().equals("0")) {
                logger.info("该用户不是管理员，不能访问后台接口，跳转到登陆页面...");
                //用的是接口，进行重重定向
                httpServletResponse.sendRedirect("/user/sign");
                return;
            }
        }
        if (havePoint) {// 如果存在"."就直接访问(不对css,js,图片等等进行过滤)
            chain.doFilter(request, response);
            return;
        } else if (user == null) {
            logger.info("不存在存在session,进行直接跳转到登陆页面...");
            //用的是接口，进行重重定向
            httpServletResponse.sendRedirect("/user/sign");
            return;
        }
    }

    /**
     * 初始化的方法
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        config = filterConfig;
        ServletContext sc = filterConfig.getServletContext();

        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
        if (cxt != null && cxt.getBean(UserService.class) != null && userMapper == null) {
            userMapper = (UserMapper) cxt.getBean(UserMapper.class);

        }
        if (cxt != null && cxt.getBean(MessageService.class) != null && messageService == null) {
            messageService = (MessageService) cxt.getBean(MessageService.class);
        }

        System.out.println("Filter初始化...");
    }
}